package com.ruoyi.dwzzzy.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description :
 * @auther :   zhanvie
 * @Date :   2021-03-21
 */
public class PDFUtils {

    private static final Float defaultFontSize = 30f;

    public static void main(String[] args) {
        try {
            addWaterMark("野狼战队", new File("E:\\3.pdf"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addWaterMark(String waterMark, File srcFile) throws IOException {
        addWaterMark(waterMark, defaultFontSize, srcFile);
    }

    public static void addWaterMark(String waterMark, Float fontSize, File srcFile) throws IOException {
        //创建新pdf文件
        File tmpPDF = new File("E:\\demo_" + srcFile.getName());
        //打开pdf文件
        PDDocument doc = PDDocument.load(srcFile);
        doc.setAllSecurityToBeRemoved(true);

        PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
        // 水印透明度
        r0.setNonStrokingAlphaConstant(0.2f);
        r0.setAlphaSourceFlag(true);


        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("font/ARIALUNI.TTF");
        PDFont font = PDType0Font.load(doc, is, true);
        is.close();

        if(fontSize == null) {
            fontSize = defaultFontSize;
        }
        //遍历pdf所有页
        for (PDPage page : doc.getPages()) {
            PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
            cs.setGraphicsStateParameters(r0);
            //水印颜色
            cs.setNonStrokingColor(188, 188, 188);
            cs.setFont(font, fontSize);
            //根据水印文字大小长度计算横向坐标需要渲染几次水印
            float h = waterMark.length() * fontSize;
            cs.beginText();
            for (int i = 1; i <= 5; i++) {
                cs.setTextMatrix(Matrix.getRotateInstance(-150, i * 200 + 80, h));
                cs.showText(waterMark);
            }
            cs.endText();
            cs.close();
        }
        doc.save(tmpPDF);
        doc.close();
    }

}